package com.cy.springcloud.hystrix;

import com.netflix.hystrix.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

/**
 * @Description: 自定义类继承HystrixCommand来实现hystrix请求
 * @ClassName: CustomHystrixCommand
 * @Author: chenyu
 * @Date: 2025/1/6 17:27
 */
public class CustomHystrixCommand extends HystrixCommand<String> {

    private final RestTemplate restTemplate;

    public CustomHystrixCommand(Setter setter, RestTemplate restTemplate) {
        super(setter);
        this.restTemplate = restTemplate;
    }

    @Override
    protected String run() throws Exception {
        //调用远程服务
        return restTemplate.getForEntity("http://01-springcloud-service-provider/hello", String.class).getBody();
    }

    /**
     *  降级熔断方法
     * @return java.lang.String
     * @date 2025/1/6 17:34
    */
    @Override
    public String getFallback() {
        //获取异常信息
        Throwable throwable = super.getExecutionException();
        System.out.println(throwable.getMessage());
        //实现服务熔断降级逻辑

        return "error";
    }
}
